using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Acme.BookStore.Domain.Entities;
using Acme.BookStore.Rfids.Dtos;
using Volo.Abp.Domain.Repositories;
using System.Linq;
using System.Linq.Dynamic.Core;

namespace Acme.BookStore.Rfids
{
    public class RfidAppService : ApplicationService, IRfidAppService
    {
        private readonly IRfidRepository _rfidRepository;
        private readonly IRepository<Rfid, string> _repository;

        public RfidAppService(IRfidRepository rfidRepository, IRepository<Rfid, string> repository)
        {
            _rfidRepository = rfidRepository;
            _repository = repository;
        }

        public async Task<PagedResultDto<RfidDto>> GetListAsync([FromQuery] PagedAndSortedResultRequestDto input, string filter = null)
        {
            var queryable = await _repository.GetQueryableAsync();

            var query = queryable
                .WhereIf(!string.IsNullOrWhiteSpace(filter), r => r.Rfid1.Contains(filter) || r.Type.Contains(filter));
            
            var totalCount = await AsyncExecuter.CountAsync(query);

            var rfids = await AsyncExecuter.ToListAsync(
                query.PageBy(input)
            );

            return new PagedResultDto<RfidDto>(
                totalCount,
                ObjectMapper.Map<List<Rfid>, List<RfidDto>>(rfids)
            );
        }

        public async Task<RfidDto> CreateAsync(CreateUpdateRfidDto input)
        {
            var id = Guid.NewGuid().ToString("N");

            var rfid = new Rfid(id)
            {
                Rfid1 = input.Rfid1,
                Type = input.Type,
                BusinessContent = input.BusinessContent,
                Rfid2 = input.Rfid2,
                Rfid3 = input.Rfid3,
                CreationDate = DateTime.Now,
                CreatorLoginName = "admin" // Placeholder, should be replaced with actual user
            };

            await _repository.InsertAsync(rfid);

            return ObjectMapper.Map<Rfid, RfidDto>(rfid);
        }

        public async Task<RfidDto> UpdateAsync(string id, CreateUpdateRfidDto input)
        {
            var rfid = await _repository.GetAsync(id);

            rfid.Rfid1 = input.Rfid1;
            rfid.Type = input.Type;
            rfid.BusinessContent = input.BusinessContent;
            rfid.Rfid2 = input.Rfid2;
            rfid.Rfid3 = input.Rfid3;

            await _repository.UpdateAsync(rfid);

            return ObjectMapper.Map<Rfid, RfidDto>(rfid);
        }

        public async Task DeleteAsync(string id)
        {
            await _repository.DeleteAsync(id);
        }
    }
} 